import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:like_button/like_button.dart';
import 'package:sainbainu/common/models/response/comment_response.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/values/colors.dart';
import 'package:sainbainu/common/widgets/widget.dart';

import '../index.dart';

typedef ReplyTap = void Function(CommentResponse item);
typedef PreviewTap = void Function(String path);
typedef LikeTap = void Function(bool flag, int? id);
typedef DelTap = void Function(int? id);
typedef UserTap = void Function(int? customerId);

class CommentItem extends GetView<ContentDetailController> {
  final CommentResponse item;
  final bool showReplyButton;
  final bool showDelIcon;
  final ReplyTap? onReplyTap;
  final PreviewTap? onPreviewTap;
  final LikeTap? onLikeTap;
  final DelTap? onDelTap;
  final UserTap? onUserTap;

  const CommentItem({
    super.key,
    required this.item,
    this.onReplyTap,
    this.showReplyButton = false,
    this.showDelIcon = false,
    this.onPreviewTap,
    this.onLikeTap,
    this.onDelTap,
    this.onUserTap,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(
        horizontal: 15,
        vertical: 5,
      ),
      child: _buildCommentItem(),
    );
  }

  /// 评论每一项
  Widget _buildCommentItem() {
    var ipText = '';
    if ((item.provinceName != null && item.provinceName!.isNotEmpty) ||
        (item.cityName != null && item.cityName!.isNotEmpty)) {
      ipText = '${item.provinceName}${item.cityName}  ';
    }
    return UserInfoCell(
      avatar: item.avatar,
      name: item.customerName ?? '',
      role: '$ipText${item.createTime ?? ''}',
      showNameAuth: item.officialFlag == 1,
      nameAuthText: item.officialName,
      nameFontSize: 14,
      roleFontSize: 12,
      avatarSize: AvatarSize.small,
      onUserTap: () => onUserTap != null ? onUserTap!(item.customerId) : null,
      rightChild: Row(
        children: [
          if (item.myFlag == 1 && showDelIcon) _buildDelIcon(),
          _buildLikeButton(),
        ],
      ),
      bottomChild: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          if (item.text != null && item.text!.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 4),
              child: ContentCardText(item.text!),
            ),
          if (item.audio != null && item.audio!.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 10),
              child: Obx(
                () => AudioWaveWidget(
                  isPlaying: controller.state.isAudioPlaying.value &&
                      item.audio == controller.state.playingUrl.value,
                  duration: item.audioDuration ?? 0,
                  durationChild: Obx(
                    () => AudioWaveDurationText(
                      '${item.audio == controller.state.playingUrl.value ? controller.state.audioSeconds.value : (item.audioDuration ?? 0)}s',
                    ),
                  ),
                  onTap: () => controller.toggleAudioPlay(
                    item.audio!,
                    item.audioDuration ?? 0,
                  ),
                ),
              ),
            ),
          if (item.image != null && item.image!.isNotEmpty)
            _buildCommentImage(),
          if (showReplyButton) _buildReplyButton(),
        ],
      ),
    );
  }

  /// 回复按钮
  Widget _buildReplyButton() {
    return Container(
      height: 26,
      margin: const EdgeInsets.only(top: 12),
      child: ElevatedButton(
        onPressed: () {
          if (onReplyTap != null) {
            onReplyTap!(item);
          }
        },
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(AppColors.page),
          foregroundColor: MaterialStateProperty.all(AppColors.active2),
          elevation: MaterialStateProperty.all(0),
          padding: MaterialStateProperty.all(
            const EdgeInsets.symmetric(vertical: 0, horizontal: 8),
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '${item.childNum ?? 0}${'回复'.tr}',
              style: const TextStyle(fontSize: 12),
            ),
            const Icon(Icons.keyboard_arrow_right, size: 16),
          ],
        ),
      ),
    );
  }

  /// 评论图片
  Widget _buildCommentImage() {
    // 图片默认宽高
    double boxW = 100.0;
    double boxH = 100.0;
    // 图片路径中获取宽高
    var sizeInfo = Util.getUrlParams(item.image!);
    if (sizeInfo.isNotEmpty &&
        (sizeInfo['w'] != null || sizeInfo['h'] != null)) {
      // 原始图片宽高和比列
      double w = double.tryParse(sizeInfo['w'] ?? sizeInfo['h']!) ?? boxW;
      double h = double.tryParse(sizeInfo['h'] ?? sizeInfo['w']!) ?? boxH;
      double aspectRatio = w / h;

      // 设置最大、最小宽度和高度
      double minWidth = 80;
      double maxWidth = 200;
      double minHeight = 80;
      double maxHeight = 140;
      // 根据宽高比调整宽度和高度
      if (aspectRatio > 1) {
        // 横图
        boxW = max(minWidth, min(maxWidth, w));
        boxH = boxW / aspectRatio;
      } else if (aspectRatio < 1) {
        // 竖图
        boxH = max(minHeight, min(maxHeight, h));
        boxW = boxH * aspectRatio;
      } else {
        // 方图
        boxW = max(minWidth, min(maxWidth, w));
        boxH = boxW;
      }
    }
    return Container(
      margin: const EdgeInsets.only(top: 10),
      width: boxW,
      height: boxH,
      child: GestureDetector(
        onTap: () {
          if (onPreviewTap != null) {
            onPreviewTap!(item.image!);
          }
        },
        child: ClipRRect(
          borderRadius: BorderRadius.circular(6),
          child: CustomImage(
            url: item.image!,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  /// 点赞
  Widget _buildLikeButton() {
    return LikeButton(
      size: 17,
      isLiked: item.giveFlag == 1,
      likeCount: item.giveNum ?? 0,
      likeBuilder: (bool isLiked) {
        String lovePath = isLiked
            ? 'assets/images/icon-num-love@.png'
            : 'assets/images/icon-num-love.png';
        return Image.asset(
          lovePath,
          width: 17,
          height: 17,
        );
      },
      countBuilder: (int? count, bool isLiked, String text) {
        return Text(
          text,
          style: const TextStyle(
            fontSize: 12,
            color: AppColors.unactive4,
          ),
        );
      },
      onTap: (isLiked) async {
        if (onLikeTap != null) {
          HapticFeedback.mediumImpact();
          onLikeTap!(!isLiked, item.commentId);
        }
        return !isLiked;
      },
    );
  }

  Widget _buildDelIcon() {
    return GestureDetector(
      onTap: () {
        if (onDelTap != null) {
          HapticFeedback.mediumImpact();
          onDelTap!(item.commentId);
        }
      },
      child: Padding(
        padding: const EdgeInsets.fromLTRB(10, 10, 15, 10),
        child: Image.asset(
          'assets/images/icon-num-del.png',
          width: 17,
          height: 17,
        ),
      ),
    );
  }
}
